import './utils/db'
import './rpc'
import { formatErrorMessage, getZodErrorMessage, type StatuAndMessageInfo } from '@packages/shared'
import { ZodError } from 'zod'
import env from './utils/env'
import routes, { headers } from './routes'
import { errorLog, infoLog } from './utils/log'

Bun.serve({
    port: env.PORT,
    routes,
    error(error) {
        errorLog(error, error.message)

        let errorMsg = '服务器异常'

        // 处理 zod 异常
        if (error instanceof ZodError)
            errorMsg = getZodErrorMessage(error)
        else
            // assert、mongoose 异常
            errorMsg = error.message

        const { code = 500, msg = '服务器异常' } = formatErrorMessage(errorMsg)


        return new Response(JSON.stringify({
            code,
            msg,
            data: error
        }), {
            status: code < 1000 ? code : 200,
            headers
        })

    }
})

infoLog(`服务器启动：http://localhost:${env.PORT}`)
